package com.gitee.flwwsg.rpc.server;

import com.gitee.flwwsg.rcp.service.AdditionService;
import com.gitee.flwwsg.rcp.service.HelloService;
import com.gitee.flwwsg.rpc.NameService;
import com.gitee.flwwsg.rpc.RPCAccessPoint;
import com.gitee.flwwsg.rpc.spi.ServiceSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.File;
import java.net.URI;

/**
 * 服务器实现
 */
public class Server {
    private static final Logger logger = LoggerFactory.getLogger(Server.class);
    public static void main(String[] args) throws Exception {
        //注册服务
        String serviceName = HelloService.class.getCanonicalName();
        String additionServiceName = AdditionService.class.getCanonicalName();
        File tmpDirFile = new File(System.getProperty("java.io.tmpdir"));
        File file = new File(tmpDirFile, "simple_rpc_name_service.data");
        HelloService helloService = new HelloServiceImpl();
        AdditionService additionService = new AdditionServiceImpl();
        logger.info("starting RPCAccessPoint");
        // 带资源的 try ，防止括号中的异常被覆盖(需要实现 AutoCloseable 接口)
        try(RPCAccessPoint rpcAccessPoint = ServiceSupport.load(RPCAccessPoint.class);
            Closeable ignored = rpcAccessPoint.startServer()) {
            NameService nameService = rpcAccessPoint.getNameService(file.toURI());
            assert nameService != null;
            logger.info("RPCAccessPoint 注册 {} 服务。。。", serviceName);
            URI uri = rpcAccessPoint.addServiceProvider(helloService, HelloService.class);
            logger.info("服务名： {}，向NamService注册。。。", serviceName);
            nameService.registerService(serviceName, uri);
            logger.info("RPCAccessPoint 注册 {} 服务。。。", additionServiceName);
            uri = rpcAccessPoint.addServiceProvider(additionService, AdditionService.class);
            logger.info("服务名： {}，向NamService注册。。。", additionServiceName);
            nameService.registerService(additionServiceName, uri);
            logger.info("开始提供服务，按任意键退出");
            System.in.read();
            logger.info("bye bye");
        }
    }
}
